//引入express模块
const express = require('express')
//创建路由器对象
const router = express.Router()
//引入pool连接池对象
const pool = require("../mysql")

//登录接口  (post  /login)
//测试地址:http://127.0.0.1:3000/user/login
router.post('/login', (req, res, next) => {
	var obj = req.body
	//console.log(obj)
	let sql = 'select uid from czy_users where uname=? and upwd=?'
	pool.query(sql, [obj.uname, obj.upwd], (err, result) => {
		if (err) return next(err)
		//console.log(result)
		if (result.length === 0) {
			res.send({ code: 401, msg: 'error login' })
		} else {
			res.send({ code: 200, msg: 'success login' })
		}
	})
})

//新增用户接口  (post  /register)
//测试地址:http://127.0.0.1:3000/user/register
router.post('/register', (req, res, next) => {
	var obj = req.body
	console.log(obj)
	//执行SQL命令
	let sql = 'insert into czy_users values (?,?,?,?,?)'
	pool.query(sql, [obj.uid, obj.uname, obj.upwd, obj.phone, obj.birthday], (err, result) => {
		if (err) return next(err)
		console.log(result)
		if (result.affectedRows === 0) {
			res.send({ code: 401, msg: 'error register' })
		} else {
			res.send({ code: 200, msg: 'success register' })
		}
	})
})

//查询用户接口 (get /:uid)
//测试地址:http://127.0.0.1:3000/user/sousuo/:lid
router.get('/sousuo/:uid',(req,res,next)=>{
    let sql = 'select*from czy_users where uid =?'
    pool.query(sql,[req.params.uid],(err,result)=>{
        if(err) return next(err)
        res.send(result)
    })
})

//修改用户接口 (post /info)
//测试地址:http://127.0.0.1:3000/user/info
router.post('/info',(req,res,next)=>{
	var obj = req.body
	console.log(obj);
	let sql = 'update czy_users set upwd=? where uid = ?'
	pool.query(sql,[obj.upwd,obj.uid]),(err,result)=>{
		if(err) return next(err)
		if(result.affectedRows == 0){
            res.send('修改失败')
        }else{
            res.send('修改成功')
        }
	}
})

//暴露出去
module.exports = router